<template>
  <div style="height: 6vh;background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">信息管理</span>
    <el-button type="primary" style="float:right;margin-top:13px;" @click="showAddDialog">新增分类</el-button>
  </div>

  <!-- 新增分类对话框 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" style="width:1000px;padding:40px;" :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="24">
          <el-form-item label="分类名称">
            <el-input placeholder="请输入分类名称" v-model="saveCategoryForm.categoryName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="24">
          <el-form-item label="排序">
            <el-input placeholder="请输入排序" v-model="saveCategoryForm.sort"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="5">
          <el-form-item label="状态">
            <el-radio-group v-model="saveCategoryForm.categoryStatus">
              <el-radio border label="启用" value="1" style="margin: 3px;"></el-radio>
              <el-radio border label="禁用" value="0" style="left: 5px"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveCategory">确定</el-button>
    </template>
  </el-dialog>

  <!-- 查询卡片 -->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="分类名称">
        <el-input placeholder="请输入分类名称" style="width:220px;"
                  v-model="searchForm.name" @keydown.enter="loadCategories"></el-input>
      </el-form-item>
      <el-form-item label="启用状态" style="width:290px;">
        <el-select placeholder="请选择启用状态" v-model="searchForm.status" @change="loadCategories">
          <el-option label="全部" value="" />
          <el-option label="启用" value="1" />
          <el-option label="禁用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loadCategories">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 分类列表表格 -->
  <el-card style="margin:20px;">
    <el-table stripe :data="filteredCategories">
      <el-table-column label="编号" prop="id" align="center" width="100"></el-table-column>
      <el-table-column label="名称" prop="name" align="center"></el-table-column>
      <el-table-column label="排序" prop="position" align="center"></el-table-column>
      <el-table-column label="创建时间" prop="createTime" align="center" width="180"></el-table-column>
      <el-table-column label="更新时间" prop="updateTime" align="center" width="180"></el-table-column>
      <el-table-column
          prop="status"
          label="启用状态"
          align="center"
          width="120"
      >
        <template #default="{ row }">
          <el-switch
              v-model="row.status"
              active-value="1"
              inactive-value="0"
              @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
          align="center"
          width="150"
      >
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="deleteCategory(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 静态数据 - 初始化分类列表
const staticCategories = ref([
  {
    id: '54',
    name: '娱乐',
    position: 1,
    status: '1',
    createTime: '2024-06-11 10:07:44',
    updateTime: '2024-06-14 14:21:56'
  },
  {
    id: '57',
    name: '美食',
    position: 99,
    status: '1',
    createTime: '2024-06-11 10:07:44',
    updateTime: '2025-06-14 14:21:56'
  },
  {
    id: '58',
    name: '阅读',
    position: 99,
    status: '0',
    createTime: '2024-06-11 10:07:44',
    updateTime: '2025-06-14 14:21:57'
  }
]);

// 响应式数据
const dialogVisible = ref(false);
const dialogTitle = ref('新增分类');
const searchForm = reactive({
  name: '',
  status: ''
});

// 分类表单
const saveCategoryForm = reactive({
  id: null,
  categoryName: '',
  sort: '',
  categoryStatus: '1'
});

// 计算属性 - 过滤后的分类列表
const filteredCategories = computed(() => {
  return staticCategories.value.filter(item => {
    const nameMatch = searchForm.name ? item.name.includes(searchForm.name) : true;
    const statusMatch = searchForm.status ? item.status === searchForm.status : true;
    return nameMatch && statusMatch;
  });
});

// 添加缺失的方法
const loadCategories = () => {
  // 这个方法可以留空，因为 filteredCategories 是计算属性会自动更新
};

// 显示新增对话框
const showAddDialog = () => {
  dialogTitle.value = '新增分类';
  resetForm();
  dialogVisible.value = true;
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
};

// 状态变更
const handleStatusChange = (row) => {
  ElMessage.success(`分类 "${row.name}" 状态已变更为 ${row.status === '1' ? '启用' : '禁用'}`);
};

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类';
  saveCategoryForm.id = row.id;
  saveCategoryForm.categoryName = row.name;
  saveCategoryForm.sort = row.position;
  saveCategoryForm.categoryStatus = row.status;
  dialogVisible.value = true;
};

// 删除分类
const deleteCategory = (row) => {
  ElMessageBox.confirm(`确定要删除分类 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = staticCategories.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      staticCategories.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 保存分类
const saveCategory = () => {
  if (!saveCategoryForm.categoryName) {
    ElMessage.error('分类名称不能为空');
    return;
  }

  if (saveCategoryForm.id) {
    // 更新现有分类
    const index = staticCategories.value.findIndex(item => item.id === saveCategoryForm.id);
    if (index !== -1) {
      const now = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-');

      staticCategories.value[index] = {
        ...staticCategories.value[index],
        name: saveCategoryForm.categoryName,
        position: saveCategoryForm.sort,
        status: saveCategoryForm.categoryStatus,
        updateTime: now
      };
    }
  } else {
    // 新增分类
    const newId = Math.max(...staticCategories.value.map(item => parseInt(item.id))) + 1;
    const now = new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    }).replace(/\//g, '-');

    staticCategories.value.unshift({
      id: newId.toString(),
      name: saveCategoryForm.categoryName,
      position: saveCategoryForm.sort,
      status: saveCategoryForm.categoryStatus,
      createTime: now,
      updateTime: now
    });
  }

  dialogVisible.value = false;
  ElMessage.success('保存成功');
};

// 重置表单
const resetForm = () => {
  saveCategoryForm.id = null;
  saveCategoryForm.categoryName = '';
  saveCategoryForm.sort = '';
  saveCategoryForm.categoryStatus = '1';
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  searchForm.status = '';
};
</script>

<style scoped>
.el-form-item {
  margin-bottom: 15px;
}
</style>